<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 参数设置提示 -->
    <el-alert
      title="注意：只允许为第三级分类设置相关参数！"
      type="warning"
      close-text="知道了"
      show-icon>
    </el-alert>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 选择商品分类 -->
      <el-form>
        <el-form-item label="选择商品分类">
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            expandTrigger="hover"
            :props="cascaderProps"
            @change="getParm">
          </el-cascader>
        </el-form-item>
      </el-form>
      <!-- 商品动态参数与静态属性显示区域 -->
      <el-tabs type="border-card" v-model="activeTabName" @tab-click="getParm()">
        <!-- 动态参数显示区域 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addManyDialogVisible = true">添加参数</el-button>
          <el-table
          :data="manyParmList"
          border
          stripe
          row-key="attr_id">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="getManyAttr(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttr(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性显示区域 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加参数按钮 -->
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addOnlyDialogVisible = true">添加属性</el-button>
          <el-table
          :data="onlyParmList"
          border
          stripe
          row-key="attr_id">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="getManyAttr(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttr(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加动态参数对话框 -->
      <el-dialog
        title="添加动态参数"
        :visible.sync="addManyDialogVisible"
        width="50%"
        @close="addManyDialogClosed">
        <el-form :model="addManyForm" :rules="manyRules"
        ref="addManyRef" label-width="120px">
          <el-form-item label="动态参数名称" prop="attr_name">
            <el-input v-model="addManyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addManyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addMany">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑动态参数对话框 -->
      <el-dialog
        title="添加动态参数"
        :visible.sync="setManyDialogVisible"
        width="50%">
        <el-form :model="setManyForm" :rules="manyRules"
        ref="setManyRef" label-width="120px">
          <el-form-item label="动态参数名称" prop="attr_name">
            <el-input v-model="setManyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="setManyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setManyAttr">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 添加静态对话框 -->
      <el-dialog
        title="添加静态属性"
        :visible.sync="addOnlyDialogVisible"
        width="50%">
        <el-form :model="addOnlyForm" :rules="onlyRules"
        ref="addOnlyRef" label-width="120px">
          <el-form-item label="静态属性名称" prop="attr_name">
            <el-input v-model="addOnlyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addOnlyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOnly">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 选中的商品分类id
      selectedKeys: [],
      // 级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品动态参数列表
      manyParmList: [],
      // 商品静态属性列表
      onlyParmList: [],
      // 默认选中的tab
      activeTabName: 'many',
      // 控制添加动态参数对话框的显示与隐藏
      addManyDialogVisible: false,
      // 控制添加静态属性对话框的显示与隐藏
      addOnlyDialogVisible: false,
      // 控制编辑动态参数对话框的显示与隐藏
      setManyDialogVisible: false,
      // 获得要添加的动态参数
      addManyForm: {
        attr_name: '',
        attr_sel: 'many'
      },
      // 获得要添加的静态属性
      addOnlyForm: {
        attr_name: '',
        attr_sel: 'only'
      },
      // 获得要编辑的动态参数
      setManyForm: {
        attr_name: '',
        attr_id: '',
        attr_sel: 'many'
      },
      // 动态参数的输入验证
      manyRules: {
        attr_name: { required: true, message: '请输入动态参数名称', trigger: 'blur' }
      },
      // 静态属性的输入验证
      onlyRules: {
        attr_name: { required: true, message: '请输入静态属性名称', trigger: 'blur' }
      }
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 判断添加参数按钮是否被禁用
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取当前选中的分类id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return []
    }
  },
  methods: {
    // 获得商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
    },
    // 获得当前商品的参数
    async getParm () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyParmList = []
        this.onlyParmList = []
        return
      }
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, { params: { sel: this.activeTabName } })
      if (res.meta.status !== 200) return this.$message.error('获取动态参数失败！')
      this.$message.success('获取动态参数成功！')
      res.data.forEach(item => {
        // 判断参数标签是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals = item.attr_vals.split(' ') : []
        // 控制参数tag输入框显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      if (this.activeTabName === 'many') {
        this.manyParmList = res.data
      } else {
        this.onlyParmList = res.data
      }
    },
    // 监视对话框，当对话框关闭进行重置
    addManyDialogClosed () {
      this.$refs.addManyRef.resetFields()
    },
    // 添加动态参数
    addMany () {
      this.$refs.addManyRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入动态参数名称！')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, this.addManyForm)
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.$message.success('添加参数成功！')
        this.addManyDialogVisible = false
        this.getParm()
      })
    },
    // 添加静态属性
    addOnly () {
      this.$refs.addOnlyRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入静态属性名称！')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, this.addOnlyForm)
        if (res.meta.status !== 201) return this.$message.error('添加静态属性失败！')
        this.$message.success('添加静态属性成功！')
        this.addOnlyDialogVisible = false
        this.getParm()
      })
    },
    // 获取要编辑的动态参数
    async getManyAttr (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { attr_sel: this.activeTabName })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败！')
      this.setManyForm.attr_name = res.data.attr_name
      this.setManyForm.attr_id = res.data.attr_id
      this.setManyDialogVisible = true
    },
    // 编辑参数
    setManyAttr () {
      this.$refs.setManyRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.setManyForm.attr_id}`, { attr_name: this.setManyForm.attr_name, attr_sel: this.activeTabName })
        if (res.meta.status !== 200) return this.$message.error('编辑参数失败！')
        this.$message.success('编辑参数成功！')
        this.setManyDialogVisible = false
        this.getParm()
      })
    },
    // 删除动态参数
    async removeAttr (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return this.$message.info('取消删除！')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败！')
      this.$message.success('删除参数成功！')
      this.getParm()
    },
    // 新增参数tag
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('编辑参数失败！')
      console.log(row.attr_vals)
      this.$message.success('编辑参数成功！')
      this.getParm()
    },
    // 切换参数tag中文本框与输入框
    showInput (row) {
      row.inputVisible = true
      // $nextTick 当页面上元素被重新渲染后才会指定会掉函数的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除指定参数tag
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('删除参数失败！')
      console.log(row.attr_vals)
      this.$message.success('删除参数成功！')
      this.getParm()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px
}
.input-new-tag {
  width: 200px;
}
</style>
